package com.keyancompany.zhongbaopingtai.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.UiThread;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;

import com.alibaba.fastjson.JSONObject;
import com.keyancompany.zhongbaopingtai.Constants;
import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.activity.ProjectDetailActivity;
import com.keyancompany.zhongbaopingtai.adapter.FindAdapter;
import com.keyancompany.zhongbaopingtai.api.CollectionAPI;
import com.keyancompany.zhongbaopingtai.api.TeamAPI;
import com.keyancompany.zhongbaopingtai.listener.IAsyncHttpResponseHandler;
import com.keyancompany.zhongbaopingtai.listener.IClickCancleListener;
import com.keyancompany.zhongbaopingtai.model.BaseModel;
import com.keyancompany.zhongbaopingtai.model.EventBusEntity;
import com.keyancompany.zhongbaopingtai.model.FindModel;
import com.keyancompany.zhongbaopingtai.utils.T;
import com.keyancompany.zhongbaopingtai.weight.IListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.Bind;
import butterknife.OnItemClick;

/**
 * 我参与 or 我发布的项目
 * Created by firefox on 2017/3/7.
 */

public class PublishPackageItemFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, IAsyncHttpResponseHandler {


    @Bind(R.id.list_view)
    IListView listView;
    @Bind(R.id.find_swipe_layout)
    SwipeRefreshLayout swipeLayout;

    private int currentPage;
    private int total;

    private static String TYPE = "TYPE";
    public static final int TYPE_CREATE = 1;
    public static final int TYPE_INJION = 2;
    private int type;

    FindAdapter mFindAdapter;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    swipeLayout.setRefreshing(false);
                    break;
                default:
                    break;
            }
        }
    };
    private boolean isFirst = true;

    /**
     * @return
     */
    public static PublishPackageItemFragment newInstance(int type) {
        PublishPackageItemFragment fragment = new PublishPackageItemFragment();
        Bundle args = new Bundle();
        args.putInt(TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_find_item;
    }

    @Override
    public void setUpViews() {
        EventBus.getDefault().register(this);
        type = getArguments().getInt(TYPE);
        initSwipeLayout(swipeLayout);
        mFindAdapter = new FindAdapter(getActivity(), new IClickCancleListener() {
            @Override
            public void clickCancle(int position) {
                if (position >= mFindAdapter.getCount())
                    return;
                FindModel item = mFindAdapter.getItem(position);
                if (item.getCollectFlag() == 1) {
                    CollectionAPI.deleteCollection(item.getPID_(),
                            new CollectionHandler(item), getLoading(-1));
                } else {
                    CollectionAPI.addCollection(item.getPID_(), new CollectionHandler(item), getLoading(-1));
                }
            }
        });

        mFindAdapter.setItemClickListener(new FindAdapter.IOnItemClickListener() {
            @Override
            public void listItemClick(FindModel item, int position) {
                if (position < mFindAdapter.getCount()) {
                    Intent intent = new Intent(context, ProjectDetailActivity.class);
                    intent.putExtra(Constants.ITEM, mFindAdapter.getItem(position));
                    intent.putExtra("res", "project");
                    intent.putExtra("position", position);
                    startActivity(intent);
                }
            }
        });

        listView.setAdapter(mFindAdapter);
        swipeLayout.setOnRefreshListener(this);
        listView.setStateListener(new IListView.SwipeLayoutState() {
            @Override
            public boolean isRefresh() {
                return swipeLayout.isRefreshing();
            }

            @Override
            public boolean isLastPage() {
                return total == currentPage;
            }

            @Override
            public void requestNextPage() {
                requestTask(++currentPage);
            }
        });

        swipeLayout.post(new Thread(new Runnable() {

            @Override
            public void run() {
                swipeLayout.setRefreshing(true);
                onRefresh();
            }
        }));
    }

    public class CollectionHandler implements IAsyncHttpResponseHandler {

        private FindModel model;

        public CollectionHandler(FindModel model) {
            this.model = model;
        }

        @Override
        public void start(int type) {

        }

        @Override
        public void success(int type, String json) {
            if (!getUserVisibleHint()) {
                return;
            }
            BaseModel base = JSONObject.parseObject(json, BaseModel.class);
            if (type == CollectionAPI.ADD_COLLECTION) {
                if (base.isSuccess())
                    model.setCollectFlag(1);
            } else {
                if (base.isSuccess())
                    model.setCollectFlag(0);
            }
            mFindAdapter.notifyDataSetChanged();
        }

        @Override
        public void failed(String error) {

        }

        @Override
        public void finish(int type) {

        }

    }

    @Override
    public void onRefresh() {

        currentPage = 1;
        total = 1;
        requestTask(currentPage);
    }


    public void requestTask(int currentPage) {
        if (type == TYPE_CREATE)
            TeamAPI.myProjectList(null, null, null, null, "" + currentPage, this, null);
        else {
            TeamAPI.projectListTreceving(null, null, null, null, "" + currentPage, this, null);
        }
    }

    @Override
    public void start(int type) {

    }

    @Override
    public void success(int type, String json) {
//        if (!getUserVisibleHint()) {
//            return;
//        }
        if (currentPage == 1) {
            mFindAdapter.clear();
            mHandler.sendEmptyMessage(1);
        } else {

        }

        BaseModel base = JSONObject.parseObject(json, BaseModel.class);
        JSONObject object = JSONObject.parseObject(base.data);
        if (!base.isSuccess()) {
            return;
        }
        if (type == TeamAPI.MY_PROJECT_LIST_MARK) {
            //{"result":"success","data":{"total":1,"current":1,"list":
            // [{"summary":1,"phone":"18600624024","setlevel":"0","invoice":"","tel":"",
            // "endTime":"2016-10-31","milestone_fill":0,"startTime":"2016-09-30 08:53:53",
            currentPage = object.getInteger(Constants.CURRENT);
            total = object.getInteger(Constants.TOTAL);
        } else if (type == TeamAPI.LIST_TRECEIVING) {
            //{"result":"sucess","token":"111111",
            // "data":{"pageNumber":1,"pageSize":20,"totalCount":2,"pageCount":1,"property":null,"keyword":null,
            // "orderBy":"createTime","orderType":"desc","list":[{"summary":1,"phone":"13324443211","setlevel":"0",
            currentPage = object.getInteger("pageNumber");
            total = object.getInteger("pageCount");

        }
        List<FindModel> list = JSONObject.parseArray(object.getString("list"), FindModel.class);
        if (mFindAdapter == null) return;
        listView.loadMoreFinish();
        if (total == currentPage) {
            listView.removeFooterView();
        }

        if (list != null && !list.isEmpty()) {
            mFindAdapter.addAllAfter(list);
            listView.findFocus();
            listView.setFocusableInTouchMode(true);
            listView.setSelection(0);
        } else {
            T.showShort(getActivity(), base.msg);
        }

    }

    @Override
    public void failed(String error) {
        swipeLayout.setRefreshing(false);
    }

    @Override
    public void finish(int type) {

    }

    /**
     * 事件订阅者自定义的接收方法
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusEntity event) {
//        //（1）将事件发布者发布的数据作为文本修改内容
//        msgFragment.setText(event.data);
        //（2）将事件发布者发布的数据作为方法执行的区分
        switch (event.getType()) {
            case EventBusEntity.Type.COLLECTION:
                mFindAdapter.replace(event.getPosition(), (FindModel) event.getItem());
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
